<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 警告框区域 -->
      <el-alert title="注意：只允许为第三级别分类设置相关参数" type="warning" show-icon></el-alert>
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类:</span>
          <el-cascader
            v-model="selectedCateKeys"
            :options="cateList"
            :props="cateProps"
            @change="cateListChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="warning"
            plain
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible=true"
          >动态参数</el-button>
          <!-- 动态参数的数据表格 -->
          <el-table :data="manyTabData" style="width: 100%" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  type="index"
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="removeHandle(index,scope.row)"
                >{{item}}</el-tag>
                <el-input
                  ref="saveTagInputRef"
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column prop="name" label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="warning"
                  icon="el-icon-edit"
                  @click="editDialog(scope.row)"
                >编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteDialog(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="warning"
            plain
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible=true"
          >静态属性</el-button>
          <!-- 静态参数的数据表格 -->
          <el-table :data="onlyTabData" style="width: 100%" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  type="index"
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="removeHandle(index,scope.row)"
                >{{item}}</el-tag>
                <el-input
                  ref="saveTagInputRef"
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputVal"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column prop="name" label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="warning"
                  icon="el-icon-edit"
                  @click="editDialog(scope.row)"
                >编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteDialog(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 这是添加分类的对话框 -->
    <el-dialog
      :title="'添加'+titleText"
      :visible.sync="addDialogVisible"
      width="30%"
      @close="addCateClose"
    >
      <!-- 添加分类的输入框 -->
      <el-form :model="addCateList" :rules="addCateRule" ref="addCateRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addCateList.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParamsHandle">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 这是编辑分类的对话框 -->
    <el-dialog
      :title="'添加'+titleText"
      :visible.sync="editDialogVisible"
      width="30%"
      @close="editCateClose"
    >
      <!-- 编辑分类的输入框 -->
      <el-form :model="editCateList" :rules="editCateRule" ref="editCateRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editCateList.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParamsHandle">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Params',
  data() {
    return {
      // 编辑分类的验证规则
      editCateRule: {
        attr_name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }]
      },

      // 编辑分类的数据
      editCateList: { attr_name: '' },

      // 控制编辑分类弹框的可见性
      editDialogVisible: false,

      // 添加分类的验证规则
      addCateRule: {
        attr_name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }]
      },

      // 添加分类的数据
      addCateList: {
        attr_name: ''
      },

      // 控制的是添加分类弹框的可见性
      addDialogVisible: false,

      // 被选择的分类数据数组
      selectedCateKeys: [],

      // 所有的数据
      cateList: [],

      // 一些配置项
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },

      // 默认选中Tab的类名
      activeName: 'many',
      onlyTabData: [],
      manyTabData: []
    }
  },
  methods: {
    // 对tag中数据的处理
    async getParams(paramsInfo) {
      const { data: res } = await this.$http.put(`categories/${paramsInfo.cat_id}/attributes/${paramsInfo.attr_id}`, {
        attr_name: paramsInfo.attr_name,
        attr_sel: paramsInfo.attr_sel,
        attr_vals: paramsInfo.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getTabList()
    },

    // 当点击tag中的删除按钮进行删除时
    removeHandle(index, paramsInfo) {
      paramsInfo.attr_vals.splice(index, 1)
      this.getParams(paramsInfo)
    },

    // 当点击输入框对应按钮触发的事件
    // 阻止多个添加的tag同时显示
    showInput(paramsInfo) {
      paramsInfo.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInputRef.$refs.input.focus()
      })
    },

    // 当点击输入框输入完成失去焦点时
    handleInputConfirm(paramsInfo) {
      if (paramsInfo.inputValue.trim().length === 0) {
        // 说明输入框之前都是空格
        paramsInfo.inputValue = ''
        paramsInfo.inputVisible = false
        return false
      }
      paramsInfo.attr_vals.push(paramsInfo.inputValue.trim())
      // console.log(paramsInfo.attr_vals)
      paramsInfo.inputValue = ''
      paramsInfo.inputVisible = false
      this.getParams(paramsInfo)
    },
    // 点击删除按钮时
    async deleteDialog(deleList) {
      const confirmMsg = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // console.log(confirmMsg)
      if (confirmMsg !== 'confirm') {
        return this.$message.info('您取消了删除')
      }
      const { data: res } = await this.$http.delete(`categories/${this.isId}/attributes/${deleList.attr_id}`)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getTabList()
    },

    // 确认提交编辑按钮式
    editParamsHandle() {
      this.$refs.editCateRef.validate(async valid => {
        const { data: res } = await this.$http.put(`categories/${this.isId}/attributes/${this.editCateList.attr_id}`, {
          attr_name: this.editCateList.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.getTabList()
        this.editDialogVisible = false
      })
    },
    // 点击编辑按钮时
    async editDialog(catList) {
      const { data: res } = await this.$http.get(`categories/${this.isId}/attributes/${catList.attr_id}`, {
        params: { attr_sel: this.activeName }
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.editCateList = res.data
      this.$message.success(res.meta.msg)
      this.getTabList()
      this.editDialogVisible = true
    },

    // 当编辑弹框关闭时
    editCateClose() {
      this.$refs.editCateRef.resetFields()
    },

    // 点击确认添加按钮
    addParamsHandle() {
      this.$refs.addCateRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`/categories/${this.isId}/attributes`, {
          attr_name: this.addCateList.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.getTabList()
        this.addDialogVisible = false
      })
    },

    // 当关闭添加对话框的关闭
    addCateClose() {
      this.$refs.addCateRef.resetFields()
    },

    // Tab栏点击触发的事件
    handleTabClick() {
      this.getTabList()
    },

    // 级连选择器数据改变
    cateListChange() {
      this.getTabList()
    },

    // 获取切换Tab的数据
    async getTabList() {
      if (this.selectedCateKeys.length !== 3) {
        // 只能选这三级数据，不是三级数据级联输入框被清空
        this.selectedCateKeys = []
        this.onlyTabData = []
        this.manyTabData = []
        return
      }
      // 当请求分类参数改变时
      const { data: res } = await this.$http.get(`/categories/${this.isId}/attributes`, {
        params: { sel: this.activeName }
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      // 对返回的数据进行处理
      // item.attr_vals = item.attr_vals.split(' ')  直接输出会存在bug  ''.split(' ')=====>[""]
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyTabData = res.data
      } else {
        this.onlyTabData = res.data
      }
    },

    // 获取所有的分类商品
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateList = res.data
    }
  },
  created() {
    this.getCateList()
  },
  computed: {
    // 控制的是添加分类的弹框的标题
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    },
    // 控制的时按钮是否禁用
    isBtnDisabled() {
      if (this.selectedCateKeys.length !== 3) {
        return true
      } else {
        return false
      }
    },
    // 获取选中动态参数的id
    // 如果是三级分类，就返回其Id
    isId() {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2]
      } else {
        return null
      }
    }
  }
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px;
  .el-cascader {
    margin-left: 20px;
  }
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>
